package sunwin.yoms.service.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import sunwin.yoms.comm.YomsException;
import sunwin.yoms.domain.person.UserDomain;
import sunwin.yoms.service.person.UserService;

import java.util.ArrayDeque;
import java.util.Collection;

/**
 * Created by mt on 2014/12/13.
 */
public class YoisUserDetailsService extends YomsUserDetailsService {
    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        YomsUserDetails userDetails = new YomsUserDetails();
        try {
            UserDomain domain = userService.getUserByLoginName(username);
            userDetails.setUsername(domain.getUserLoginName());
            userDetails.setPassword(domain.getUserLoginPassword());
            userDetails.setNickname(domain.getUserNickname());
            userDetails.setUserid(domain.getUserId());
            userDetails.setAvatar(domain.getUserHead());
            userDetails.setRealname(domain.getUserName());
            userDetails.setAuthorities(getAuthority(domain.getUserId()));
        } catch (YomsException e) {
            throw new UsernameNotFoundException("无法查找到用户");
        }
        return userDetails;
    }

    /**
     * 获取权限
     *
     * @param uid
     * @return
     * @throws YomsException
     */
    @Override
    protected Collection<GrantedAuthority> getAuthority(int uid) {
        Collection<GrantedAuthority> authoritys = new ArrayDeque<>();
        authoritys.add(new YomsAuthority("ROLE_YOIS"));
        return authoritys;
    }
}